package com.matt.service.impl;

import com.alibaba.fastjson.JSON;
import com.dotflat.util.AssertUtil;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.page.PagerQuery;
import com.matt.commons.utils.RemoteCallUtil;
import com.matt.domain.*;
import com.matt.domain.courseV2.po.ChildrenCountPO;
import com.matt.domain.vo.ContractVo;
import com.matt.domain.vo.ContractVoV2;
import com.matt.foundation.constant.ChildrenConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.utils.HttpClientUtil;
import com.matt.foundation.vo.children.BabyNClassInfoVO;
import com.matt.repository.*;
import com.matt.repository.record.ChildrenNurseryInfoRecordRepository;
import com.matt.service.ChildrenService;
import com.matt.service.NurseryInfoRecordService;
import com.matt.service.remoteCall.DTO.ContractInfoDTO;
import com.tuo51.foudation.utils.MapConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2018/10/31
 * *******************************
 */
@Service
@Slf4j
public class NurseryInfoRecordServiceImpl implements NurseryInfoRecordService {

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private ChildrenExtendInfoRepository childrenExtendInfoRepository;

    @Autowired
    private ChildrenNurseryInfoRecordRepository childrenNurseryInfoRecordRepository;

    @Autowired
    private WorkDateRepository workDateRepository;

    @Autowired
    private ExtendInfoRepository extendInfoRepository;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private ChildrenContractInfoRecordRepository childrenContractInfoRecordRepository;

    @Value("${server.crm.url}")
    private String crmServerURL;

    @Override
    public void updateContractDate(StaffDTO staffDTO, int day1) {
        List<Children> childrenList = childrenRepository.findAllByAreaId(staffDTO.getAreaId());
        List<String> ids = childrenList.stream().map(k -> k.getId()).collect(Collectors.toList());
        List<ChildrenExtendInfo> extendInfoList = childrenExtendInfoRepository.findByChildrenIdIn(ids);

        WorkDate workDate = workDateRepository.getWorkDateAscDay(new Date(), day1);
        //时间内多少天工作日
        int day = workDateRepository.findByWorkDateDay(new Date(), workDate.getWorkDate());

        if (day > 0) {
            List<ChildrenNurseryInfoRecord> ret = extendInfoList.stream().map(o -> {
                ChildrenNurseryInfoRecord po = new ChildrenNurseryInfoRecord();
                if (o.getNurseryEndDate().getTime() >= workDate.getWorkDate().getTime()) {
                    po.setChildrenId(o.getChildrenId());
                    po.setCreatedName(o.getChildrenName());
                    po.setStatus(ChildrenConstant.CheckStatus.LEAVE.codeOf());
                    po.setHealthyStatus(0);
                    po.setBeginDate(new Date());
                    po.setEndDate(workDate.getWorkDate());
                    po.setEffectDay(day);
                    po.setType(ChildrenConstant.SurplusType.EXTENDED_RECORDS.codeOf());
                    po.setNurseryOriginalEndDate(o.getNurseryEndDate());
                    WorkDate workDate1 = workDateRepository.getWorkDateAscDay(o.getNurseryEndDate(), day);
                    po.setNurseryEndDate(workDate1.getWorkDate());
                    po.setCreatedBy(staffDTO.getId());
                    po.setCreatedName(staffDTO.getRealName());
                    po.setSurplusOriginalLeaveDay(o.getSurplusLeaveDay());
                    po.setSurplusLeaveDay(o.getSurplusLeaveDay());
                    //修改宝宝合同日期
                    o.setNurseryEndDate(po.getNurseryEndDate());
                }
                return po;
            }).collect(Collectors.toList());

            childrenNurseryInfoRecordRepository.saveAll(ret);
            childrenExtendInfoRepository.saveAll(extendInfoList);
        }
    }

    @Override
    public ChildrenExtendInfo updateChildrenIdContractDate(String ticket,StaffDTO staffDTO, String childrenId, int day) {
        ChildrenExtendInfo childrenExtendInfo = childrenExtendInfoRepository.findByChildrenId(childrenId);
        WorkDate workDate = workDateRepository.getWorkDateAscDay(childrenExtendInfo.getNurseryEndDate(), day);
        if (AssertUtil.isEmpty(childrenExtendInfo) || day <= 0) {
            throw new BusinessException(ErrorCode.UNDEFINED, "参数异常");
        }
        ChildrenNurseryInfoRecord po = new ChildrenNurseryInfoRecord();
        po.setChildrenId(childrenExtendInfo.getChildrenId());
        po.setCreatedName(childrenExtendInfo.getChildrenName());
        po.setStatus(ChildrenConstant.CheckStatus.LEAVE.codeOf());
        po.setHealthyStatus(0);
        po.setBeginDate(new Date());
        po.setEndDate(DateUtil.addDay(new Date(), day));
        po.setEffectDay(day);
        po.setType(ChildrenConstant.SurplusType.EXTENDED_RECORDS.codeOf());
        po.setNurseryOriginalEndDate(childrenExtendInfo.getNurseryEndDate());
        po.setNurseryEndDate(workDate.getWorkDate());
        if (AssertUtil.isNotEmpty(workDate)){
            po.setNurseryEndDate(workDate.getWorkDate());
        }else {
            po.setNurseryEndDate(DateUtil.addDay(childrenExtendInfo.getNurseryEndDate(),day));
        }
        po.setCreatedBy(staffDTO.getId());
        po.setSurplusOriginalLeaveDay(childrenExtendInfo.getSurplusLeaveDay());
        po.setSurplusLeaveDay(childrenExtendInfo.getSurplusLeaveDay());
        po.setCreatedName(staffDTO.getRealName());
        po.setRemark(staffDTO.getRealName() + "老师手动接口添加");
        //修改宝宝合同日期
        childrenExtendInfo.setNurseryEndDate(po.getNurseryEndDate());
        childrenNurseryInfoRecordRepository.save(po);

        //修改合同请假天数
        List<ChildrenContractInfoRecord> contractInfoRecordList = childrenService.getChildrenContractInfoRecord( staffDTO, childrenId, new Date(), day, 3);

        childrenExtendInfoRepository.save(childrenExtendInfo);
        return childrenExtendInfo;
    }

    @Override
    public Page<ChildrenNurseryInfoRecord> getList( String childrenId, String beginDate, String endDate, PagerQuery pagerQuery) {
        PageRequest pageRequest = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize(),
                Sort.by("created").descending());
        Specification<ChildrenNurseryInfoRecord> specification = new Specification<ChildrenNurseryInfoRecord>() {
            @Override
            public Predicate toPredicate(Root<ChildrenNurseryInfoRecord> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(childrenId)) {
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("childrenId"), childrenId)));
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
                    predicates.add(criteriaBuilder.ge(root.get("beginDate").as(Long.class), Long.parseLong(sdf.format(DateUtil.parseToDate(beginDate)))));
                    predicates.add(criteriaBuilder.le(root.get("endDate").as(Long.class), Long.parseLong(sdf.format(DateUtil.parseToDateMilisV2(endDate)))));
                }

                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.desc(root.get("created")));
                return query.getRestriction();
            }
        };
        Page<ChildrenNurseryInfoRecord> page = childrenNurseryInfoRecordRepository.findAll(specification, pageRequest);
        return page;
    }

    @Override
    public void getWorkDate() {
        //上班日
        String url = "https://api.apihubs.cn/holiday/get?workday=1&cn=1&size=365";
        String r = null;
        try {
            r = HttpClientUtil.sendGet(url);
            Map<String, Object> map = JSON.parseObject(r, Map.class);
            Map<String, Object> map1 = (Map<String, Object>) map.get("data");
            List<Map<String, Object>> mapList = (List<Map<String, Object>>) map1.get("list");
            List<WorkDate> workDates = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            for (int i = 0; i < mapList.size(); i++) {
                WorkDate workDate = workDateRepository.findByWorkDate(sdf.parse(String.valueOf(mapList.get(i).get("date"))));
                if (Objects.nonNull(workDate)) {
                    continue;
                }
                workDate = new WorkDate();
                workDate.setType(0);
                workDate.setWorkDate(sdf.parse(String.valueOf(mapList.get(i).get("date"))));
                workDates.add(workDate);
            }
            workDateRepository.saveAll(workDates);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public Map getBalance(StaffDTO staffDTO, String childrenId, String beginDate, String endDate, PagerQuery pagerQuery) {
        Children children = childrenRepository.getOne(childrenId);

        Map attendanceMap = new HashMap();
        attendanceMap.put("areaId", children.getAreaId());
        attendanceMap.put("clientelesId", children.getCrmClienteleId());
        //合同当月的应出勤数
        List<Map> mapList1 = RemoteCallUtil.callOfList(crmServerURL + "/api/other_system/attendance_count", attendanceMap, null, Map.class, "获取合同信息失败");

        Integer shouldAttendanceCount = 0;

        for (int k = 0; k <mapList1.size() ; k++) {
            String clienteleId = String.valueOf(mapList1.get(k).get("clienteleId"));
            if (StringUtils.equals(children.getCrmClienteleId(),clienteleId)){
                shouldAttendanceCount = (Integer) mapList1.get(k).get("count");
            }
        }

        Page<ChildrenNurseryInfoRecord> page = getList( childrenId, beginDate, endDate, pagerQuery);

        //普通课程
        int type0 = 0;
        //延长合同
        int type1 = 0;
        //入户扣课
        int type2 = 0;

        for (int i = 0; i < page.getContent().size(); i++) {
            if (page.getContent().get(i).getType() == 0 && (page.getContent().get(i).getStatus() == 1 || page.getContent().get(i).getStatus() == 2)) {
                type0 = type0 + page.getContent().get(i).getEffectDay();
            }
            if (page.getContent().get(i).getType() == 1) {
                type1 = type1 + page.getContent().get(i).getEffectDay();
            }
            if (page.getContent().get(i).getType() == 2) {
                type0 = type2 + type0;
                type2 = type2 + (~((page.getContent().get(i).getEffectDay() / 2) - 1));
            }
        }
        Map map = new HashMap();
        map.put("areaId", children.getAreaId());
        map.put("clienteleId", children.getCrmClienteleId());
        map.put("date", beginDate);
        //查询用户合同在开始时间内的托班合同
        List<ContractVoV2> callOfList = RemoteCallUtil.callOfList(crmServerURL + "/api/other_system/get_clienteleId_contract_list", map, null, ContractVoV2.class, "获取合同信息失败");
        for (int i = 0; i < callOfList.size(); i++) {
            //合同的最大请假数
            Integer  surplusOriginalLeaveDay = childrenContractInfoRecordRepository.getMaxSurplusOriginalLeaveDay(callOfList.get(i).getId());
            if (surplusOriginalLeaveDay>0){
                callOfList.get(i).setSurplusOriginalLeaveDay(surplusOriginalLeaveDay);
            }
        }

        Map m = new HashMap();
        //合同原始工作日天数
        m.put("initialDay", shouldAttendanceCount);
        //课时顺延数量
        m.put("reduceAddDay", type1 + type2);
        //今日之后工作日数量
        m.put("attendDay", type0);
        //合同集合
        m.put("contractList", callOfList);

        m.put("page", page);
        return m;
    }


    @Override
    public List<Map<String, Object>> getMonthInfo(StaffDTO staffDTO, String classId, String name, String beginDateStr, String endDateStr) {
        //班级学生信息
        List<BabyNClassInfoVO> babyClassInfoList = childrenService.getChildrenClassInfoForCrm(staffDTO.getAreaId(), name, classId);
        List<String> ids = babyClassInfoList.stream().map(k -> k.getId()).collect(Collectors.toList());
        //学生考勤列表
        List<ChildrenNurseryInfoRecord> records = extendInfoRepository.findAllByChildrenClassId(classId, beginDateStr, endDateStr,ids);
        Map<String,Map<String,ChildrenNurseryInfoRecord>> recordMapList = new HashMap<>();
        records.stream().forEach(o->{
            if (null == recordMapList.get(o.getChildrenId())){
                Map<String,ChildrenNurseryInfoRecord> map = new HashMap<>();
                map.put(DateUtil.formatDayToStr(o.getCreated()),o);
                recordMapList.put(o.getChildrenId(),map);
            }else {
                Map<String,ChildrenNurseryInfoRecord> map = recordMapList.get(o.getChildrenId());
                map.put(DateUtil.formatDayToStr(o.getCreated()),o);
            }
        });

        //工作时间列表
        Date beginDate = DateUtil.parseToDate(beginDateStr);
        Date endDate = DateUtil.parseToDate(endDateStr);
        endDate = DateUtil.plusDaysToDate(endDate, 1); // 打个热补丁， 含头不含尾！！！

        List<ChildrenCountPO> childrenCountPOList = extendInfoRepository.countAllEffectedDayByChildrenId(ids, beginDate, endDate);


        long futureCount = workDateRepository.countAllByWorkDateBetween(beginDate, endDate);


        double monthScale = DateUtil.betweenMonthsV2(endDate, beginDate); //计算月数量
        List<WorkDate> workDateDayList = workDateRepository.findByWorkDateDayList(beginDate, endDate);

        //所有天
        List<String> dateList = DateUtil.getDay(beginDate, endDate);

        //合同当月的应出勤数
        List<ContractInfoDTO> contractInfos = getCRMAttendenceInfo(staffDTO.getAreaId(), beginDateStr);
        Map<String, List<ContractInfoDTO>> metaCache = contractInfos.stream().collect(Collectors.toMap(
                ContractInfoDTO::getClienteleId,
                o -> Arrays.asList(o),
                (newObj, oldObj) ->{
                    ArrayList ret = new ArrayList();
                    ret.addAll(oldObj);
                    ret.addAll(newObj);
                    return ret;
                }));

        List<Map<String, Object>> result = new ArrayList<>();

        for (int i = 0; i < babyClassInfoList.size(); i++) {
            Map babyMonthInfo = new HashMap();
            BabyNClassInfoVO baby = babyClassInfoList.get(i);
            babyMonthInfo.put("id", baby.getId());
            babyMonthInfo.put("name", baby.getName());
            //正常考勤
            int q1 = 0;
            //请假考勤
            int q2 = 0;
            //病假考勤
            int q3 = 0;
            //总天数
            int q4 = 0;
            for (int j = 0; j < dateList.size(); j++) {
                Map dayInfo = new HashMap();
                dayInfo.put("isWork", isHoliday(workDateDayList, dateList.get(j)));
                babyMonthInfo.put(dateList.get(j), dayInfo);
                if (null != recordMapList.get(baby.getId())){
                    ChildrenNurseryInfoRecord record =  recordMapList.get(baby.getId()).get(dateList.get(j));
                    if (null != record){
                        //加入所有信息
                        dayInfo.putAll(MapConvertUtil.obejctToMap(record, true));
                        if (record.getStatus() == 1 || record.getStatus() == 2) {
                            q1++;
                            q4++;
                        } else if (record.getStatus() == 4) {
                            if (record.getHealthyStatus() == 1) {
                                q3++;
                            } else {
                                q2++;
                            }
                        } else if (record.getStatus() == 5) {
                            q1++;
                            q4 += record.getEffectDay();
                        }
                    }
                }
            }

            List<ContractInfoDTO>  metas = metaCache.get(baby.getCrmClienteleId());

            ContractInfoDTO meta = null;
            if (metas != null && metas.size() > 0){
                meta = metas.get(0);
            }

            attachMetaInfo(meta, babyMonthInfo, workDateDayList.size(), monthScale, q1, q2, q3, q4);

            if (metas != null && metas.size() >1 ){
                log.debug("got a multiple contract children  ====  " + metas.size());
            }
            childrenCountPOList.stream().forEach(o->{
                if (StringUtils.equals(o.getChildrenId(),baby.getId())){
                    babyMonthInfo.put("contractFullCount", o.getCount());  //合同期内消课数
                    //预期合同未来的数量
                    babyMonthInfo.put("contractPreferCount", o.getCount().intValue() + futureCount);  //预计合同总出勤数
                }
            });




            result.add(babyMonthInfo);
        }

        return result;
    }


    @Override
    public List<Map<String, Object>> exportMonthInfoSheet(StaffDTO staffDTO, String classId, String name, String beginDateStr, String endDateStr) {
        List<Map<String, Object>> mapList = new ArrayList<>();

        //班级学生信息
        List<BabyNClassInfoVO> babyClassInfoList = childrenService.getChildrenClassInfoForCrm(staffDTO.getAreaId(), name, classId);
        List<String> ids = babyClassInfoList.stream().map(k -> k.getId()).collect(Collectors.toList());
        //学生考勤列表
        List<ChildrenNurseryInfoRecord> records = extendInfoRepository.findAllByChildrenClassId(classId, beginDateStr, endDateStr,ids);
        Map<String,Map<String,ChildrenNurseryInfoRecord>> recordMapList = new HashMap<>();
        records.stream().forEach(o->{
            if (null == recordMapList.get(o.getChildrenId())){
                Map<String,ChildrenNurseryInfoRecord> map = new HashMap<>();
                map.put(DateUtil.formatDayToStr(o.getCreated()),o);
                recordMapList.put(o.getChildrenId(),map);
            }else {
                Map<String,ChildrenNurseryInfoRecord> map = recordMapList.get(o.getChildrenId());
                map.put(DateUtil.formatDayToStr(o.getCreated()),o);
            }
        });


        //工作时间列表
        Date beginDate = DateUtil.parseToDate(beginDateStr);
        Date endDate = DateUtil.parseToDate(endDateStr);
        endDate = DateUtil.plusDaysToDate(endDate, 1); // 打个热补丁， 含头不含尾！！！

        List<ChildrenCountPO> childrenCountPOList = extendInfoRepository.countAllEffectedDayByChildrenId(ids, beginDate, endDate);


        long futureCount = workDateRepository.countAllByWorkDateBetween(beginDate, endDate);

        double monthScale = DateUtil.betweenMonthsV2(endDate, beginDate); //计算月数量
        List<WorkDate> workDateDayList = workDateRepository.findByWorkDateDayList(beginDate, endDate);
        //所有天
        List<String> dateList = DateUtil.getDay(beginDate, endDate);

        //合同当月的应出勤数
        List<ContractInfoDTO> contractInfos = getCRMAttendenceInfo(staffDTO.getAreaId(), beginDateStr);
        Map<String, List<ContractInfoDTO>> metaCache = contractInfos.stream().collect(Collectors.toMap(
                ContractInfoDTO::getClienteleId,
                o -> Arrays.asList(o),
                (newObj, oldObj) ->{
                    ArrayList ret = new ArrayList();
                    ret.addAll(oldObj);
                    ret.addAll(newObj);
                    return ret;
                }));

        for (int i = 0; i < babyClassInfoList.size(); i++) {
            Map babyMonthInfo = new HashMap();

            BabyNClassInfoVO baby = babyClassInfoList.get(i);

            babyMonthInfo.put("id", baby.getId());
            babyMonthInfo.put("name", baby.getName());

            //正常考勤
            int q1 = 0;
            //请假考勤
            int q2 = 0;
            //病假考勤
            int q3 = 0;
            //考勤统计
            int q4 = 0;

            for (int j = 0; j < dateList.size(); j++) {
                if (null != recordMapList.get(baby.getId())){
                    ChildrenNurseryInfoRecord record =  recordMapList.get(baby.getId()).get(dateList.get(j));
                    if (null != record){
                        String description = "";
                        if (!isHoliday(workDateDayList,dateList.get(j))){
                            description = "节假日：";
                        }
                        if (record.getStatus() == 1 || record.getStatus() == 2) {
                            q1++;
                            q4++;
                            description += "出勤";
                        } else if (record.getStatus() == 4) {
                            if (record.getHealthyStatus() == 1) {
                                q3++;
                                description += "病假";
                            } else {
                                q2++;
                                description += "请假";
                            }
                        }else if (record.getStatus() == 5) {
                            q1++;
                            q4= q4 + record.getEffectDay();
                            description += "入户-" + record.getEffectDay();
                        }

                        babyMonthInfo.put(dateList.get(j), description);
                    }
                }
            }

            List<ContractInfoDTO>  metas = metaCache.get(baby.getCrmClienteleId());

            ContractInfoDTO meta = null;
            if (metas != null && metas.size() > 0){
                meta = metas.get(0);
            }

            attachMetaInfo(meta, babyMonthInfo, workDateDayList.size(), monthScale, q1, q2, q3, q4);

            //TODO: 追加额外的meta费用
            if (metas != null && metas.size() >1 ){
                log.debug("got a multiple contract children  ====  " + metas.size());
            }
            childrenCountPOList.stream().forEach(o->{
                if (StringUtils.equals(o.getChildrenId(),baby.getId())){
                    babyMonthInfo.put("contractFullCount", o.getCount());  //合同期内消课数
                    //预期合同未来的数量
                    babyMonthInfo.put("contractPreferCount", o.getCount().intValue() + futureCount);  //预计合同总出勤数
                }
            });



            mapList.add(babyMonthInfo);
        }
        return mapList;
    }

    public static boolean isHoliday(List<WorkDate> workDateDayList, String date) {
        for (int i = 0; i < workDateDayList.size(); i++) {
            if (StringUtils.equals(DateUtil.formatDayToStr(workDateDayList.get(i).getWorkDate()), date)) {
                return true;
            }
        }
        return false;
    }

    private List<ContractInfoDTO> getCRMAttendenceInfo(String areaId, String beginDate){

        Map params = new HashMap();
        params.put("areaId", areaId);
        params.put("date", beginDate);

        //合同当月的应出勤数
        List<ContractInfoDTO> mapList1 = RemoteCallUtil.callOfList(crmServerURL + "/api/other_system/attendance_count", params, null, ContractInfoDTO.class, "获取合同信息失败");

        return mapList1;
    }

    public List<ContractVo> clientelesIdByContractList(String clientelesIds){

        Map params = new HashMap();
        params.put("clientelesIds", clientelesIds);
        //合同当月的应出勤数
        List<ContractVo> mapList1 = RemoteCallUtil.callOfList(crmServerURL + "/api/other_system/clientelesIdByContractList", params, null, ContractVo.class, "获取合同信息失败");
        return mapList1;
    }

    /**
     *
     * @param meta
     * @param babyMonthInfo
     * @param dayCount   需要出勤的天数
     * @param monthScale
     * @param recordCount
     * @param sickCount
     * @param leaveCount
     * @param attendanceCount
     */
    private void attachMetaInfo(ContractInfoDTO meta, Map babyMonthInfo, Integer dayCount, double monthScale,
                                Integer recordCount,  Integer leaveCount,Integer sickCount, Integer attendanceCount){

        if (meta == null){
            meta = new ContractInfoDTO();
        }

        if (dayCount <= 0){
            //应出勤天数
            babyMonthInfo.put("shouldAttendanceCount", "0" );
            //出勤率
            babyMonthInfo.put("attendanceProbability",  "0%");
        }else {
            babyMonthInfo.put("shouldAttendanceCount", dayCount);
            //出勤率
            babyMonthInfo.put("attendanceProbability", (int)((Double.valueOf(recordCount) / dayCount)*100) + "%");
        }
        //正常考勤统计
        babyMonthInfo.put("attendanceCount", attendanceCount);
        //请假考勤统计
        babyMonthInfo.put("sickCount", sickCount);
        //病假考勤统计
        babyMonthInfo.put("leaveCount", leaveCount);

        //当月已产生的合同金额,消课总金额
        double amountDuration = meta.getMonthAmount() * monthScale;
        double unitPrice = amountDuration/dayCount;

        // (meta.getMonthPrice() / meta.getDayCount()) * attendanceCount;
        double count = unitPrice * attendanceCount;
        if (count > 0){
            babyMonthInfo.put("practicalAmount", String.format("%.2f",count));
        }else {
            babyMonthInfo.put("practicalAmount","0.0");
        }

        if (meta.getMonthAmount() > 0){
            babyMonthInfo.put("totalAmount", String.format("%.2f", meta.getMonthAmount()));
        }else {
            babyMonthInfo.put("totalAmount", "0");
        }
        babyMonthInfo.put("contractTotalAmount", meta.getTotalAmount());   //合同总额
        babyMonthInfo.put("surplusLeaveDay", meta.getSurplusLeaveDay());  //可延课数量
    }



    @Override
    public List<ChildrenNurseryInfoRecord> findByChildrenIdIn(String[] childrenIds) {
        return childrenNurseryInfoRecordRepository.findByChildrenIdIn(childrenIds);
    }

    @Override
    public Page<ChildrenNurseryInfoRecord> getListByAreaId(String areaId, String childrenName, String beginDate, String endDate, PagerQuery pagerQuery) {
        PageRequest pageRequest = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize(),
                Sort.by("created").descending());
        Specification<ChildrenNurseryInfoRecord> specification = new Specification<ChildrenNurseryInfoRecord>() {
            @Override
            public Predicate toPredicate(Root<ChildrenNurseryInfoRecord> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
//                if (StringUtils.isNotBlank(childrenId)) {
//                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("childrenId"), childrenId)));
//                }


                if (StringUtils.isNotBlank(areaId)) {
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("areaId"), areaId)));
                }
                if (StringUtils.isNotBlank(childrenName)){
                    predicates.add(criteriaBuilder.and(criteriaBuilder.like(root.get("childrenName"), "%" + childrenName + "%")));
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
                    predicates.add(criteriaBuilder.ge(root.get("beginDate").as(Long.class), Long.parseLong(sdf.format(DateUtil.parseToDate(beginDate)))));
                    predicates.add(criteriaBuilder.le(root.get("endDate").as(Long.class), Long.parseLong(sdf.format(DateUtil.parseToDateMilisV2(endDate)))));
                }

                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.desc(root.get("created")));
                return query.getRestriction();
            }
        };
        Page<ChildrenNurseryInfoRecord> page = childrenNurseryInfoRecordRepository.findAll(specification, pageRequest);
        return page;
    }
}
